import React, { Component } from 'react'
import { connect } from 'react-redux'
import Proptypes from 'prop-types'
import { projectLabelView as projectDuck } from 'ducks'
import Group from './group'
import BlockReg from './blockReg'
import ItemDropdown from './itemDropdwon'

class SelectClassView extends Component {
  static propTypes = {
    activeClass: Proptypes.string,
    classes: Proptypes.object.isRequired,
    setActiveClass: Proptypes.func.isRequired,
  }

  static defaultProps = {
    activeClass: '',
  }

  state = {
    options: [],
  }

  componentDidMount() {
    const { classes, setActiveClass } = this.props
    const options = []
    const keys = Object.keys(classes)
    keys.forEach((key) => {
      options.push({
        key: classes[key].id,
        value: classes[key].id,
        text: classes[key].name,
        type: classes[key].type,
      })
    })
    this.setState({ options })
    setActiveClass(options[0].value)
  }

  render() {
    const { setActiveClass, activeClass } = this.props
    const { options } = this.state
    return (
      <React.Fragment>
        <Group title="类型">
          <BlockReg>
            <ItemDropdown
              options={options}
              value={activeClass}
              action={(e, { value }) => setActiveClass(value)}
            />
          </BlockReg>
        </Group>
      </React.Fragment>
    )
  }
}

const mapStateToProps = state => ({
  classes: projectDuck.selectors.classes(state),
  activeClass: projectDuck.selectors.activeclass(state),
})

const mapDispatchToProps = {
  setActiveClass: projectDuck.creators.actionSetActiveClass,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(SelectClassView)
